package bjut.core.zookeeper;

import bjut.core.extension.ExtensionLoader;
import bjut.core.Message.RpcRequest;
import bjut.core.interfaces.LoadBalance;
import bjut.core.interfaces.ServiceDiscovery;
import bjut.core.utils.CuratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.util.CollectionUtils;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * @Author: zhuzhiming
 * @Date: 2022/4/22 17:07
 */
@Slf4j
public class ZkServiceDiscoveryImpl implements ServiceDiscovery {

    private final LoadBalance loadBalance;

    public ZkServiceDiscoveryImpl() {
        this.loadBalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension("random");
    }

    @Override
    public InetSocketAddress lookupService(RpcRequest rpcRequest) {

        String rpcServiceName = rpcRequest.getRpcServiceName();

        CuratorFramework zkClient = CuratorUtil.getZkClient();
        List<String> serviceAddressList = CuratorUtil.getChildrenNodes(zkClient, rpcServiceName);
        if (CollectionUtils.isEmpty(serviceAddressList)) {
            throw new RuntimeException("no such service " + rpcServiceName);
        }

        String serviceAddress = loadBalance.selectService(serviceAddressList, rpcRequest);
        String[] socketAddress = serviceAddress.split(":");

        return new InetSocketAddress(socketAddress[0], Integer.parseInt(socketAddress[1]));


    }
}
